//
// Created by Yun on 2025/3/2.
//

#include "bsp_i2c.h"


uint8_t Bsp_I2C_Init(void* pI2CHwCfg)
{

    if(pI2CHwCfg == NULL) return BSP_ERROR;

    I2C_Hw_Cfg_TypeDef *pstHwCfg = (I2C_Hw_Cfg_TypeDef*)pI2CHwCfg;

    // 使能I2C时钟
    if     (pstHwCfg->stHI2C.Instance == I2C1)  __HAL_RCC_I2C1_CLK_ENABLE();
    else if(pstHwCfg->stHI2C.Instance == I2C2)  __HAL_RCC_I2C2_CLK_ENABLE();
    else                                        return BSP_ERROR;

    // 初始化GPIO
    CHECK_BSP_STATUS(Bsp_Gpio_Init(&pstHwCfg->stSCL));
    CHECK_BSP_STATUS(Bsp_Gpio_Init(&pstHwCfg->stSDA));

    // 初始化I2C
    if(HAL_I2C_Init(&pstHwCfg->stHI2C) != HAL_OK) return BSP_ERROR;

    return BSP_OK;
}

uint8_t Bsp_I2C_Transmit(void* pSpiHwCfg, uint16_t u16Address,uint8_t* pu8TxData,
                         uint16_t u16Len, uint32_t u32TimeOut)
{
    if(pSpiHwCfg == NULL) return BSP_ERROR;

    I2C_Hw_Cfg_TypeDef *pstHwCfg = (I2C_Hw_Cfg_TypeDef*)pSpiHwCfg;

    if(HAL_I2C_Master_Transmit(&pstHwCfg->stHI2C,
                               u16Address,
                               pu8TxData,
                               u16Len,
                               u32TimeOut) != HAL_OK) return BSP_ERROR;

    return BSP_OK;
}

uint8_t Bsp_I2C_Receive(void* pSpiHwCfg, uint16_t u16Address,uint8_t* pu8RxData,
                        uint16_t u16Len, uint32_t u32TimeOut)
{
    if(pSpiHwCfg == NULL) return BSP_ERROR;

    I2C_Hw_Cfg_TypeDef *pstHwCfg = (I2C_Hw_Cfg_TypeDef*)pSpiHwCfg;

    if(HAL_I2C_Master_Receive(&pstHwCfg->stHI2C,
                              u16Address,
                              pu8RxData,
                              u16Len,
                              u32TimeOut) != HAL_OK) return BSP_ERROR;

    return BSP_OK;
}

I2c_Interface_TypeDef stBspI2CInterface = {
        .Init = Bsp_I2C_Init,
        .Transmit = Bsp_I2C_Transmit,
        .Receive = Bsp_I2C_Receive
};
